/**
 * 移动护理权限审核
 * creator:JYW
 * date:2020-11-27
 */
import React from 'react';
import { Select, Input, Row, Col, Button, Spin, message, Divider, Icon, Card, Tabs, Table } from 'antd';
import { $http } from '../../../containers/config/https';
import PubilcTablePagination from '../../common/PubilcTablePagination.jsx';
import TipHeader from 'pages/Cashier/charges/component/TipHeader';
import { DeviceUtil } from 'tools/index';
import store from 'store';
import PatientList from '../Patient/PatientList';
import { Util, dayFormat } from 'tools/index';
import moment from 'moment';
import RangeDatePicker from 'components/rangePicker/index';
import 'pages/Cashier/charges/style/style.less';
import './style/index.less'; //引入样式
import { $loadTemplate } from '../../lodop/Common/Print.js';
import { getLodop } from '../../lodop/Common/LodopFuncs.js';
import { $fastReportTemplate } from '../../lodop/Common/FastReportPrint.js';
const { Option } = Select;
const { TabPane } = Tabs;
let user;
class NurseEmrRecord extends React.Component {
	constructor({ history }) {
		user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
		var patientData = window.sessionStorage.patientData ? JSON.parse(window.sessionStorage.patientData) : {};
		var date = new Date();
		super();
		this.history = history;
		this.state = {
			iconType: 'double-left',
			leftspan: 5,
			rightspan: 19,
			userInfo: {},
			patient: [],
			selectPatient: {},
			templateList: [], //模板列表
			patientData: patientData,
			columns: {}, //表格数据列头
			dataSource: [], //表格数据
			total: 0,
			page: 1,
			pageSize: 20,
			emrRecordID: '',
			activeKey: '0',
			iEMRTemplateflag:'',
			endColumns: [
				{
					title: '时间',
					dataIndex: 'creatDateTime',
					key: 'creatDateTime',
					align: 'left',
					width: '140px'
				},
				{
					title: '填写人',
					dataIndex: 'creatUserName',
					key: 'creatUserName',
					align: 'left',
					width: '140px'
				}
			],
			admDateFrom: moment().subtract(14, 'days').format(dayFormat),
			admDateTo: moment(date).format(dayFormat)
		};
	}
	componentDidMount() {
		this.getTemplateList();
		this.onClickRowPublicTop({});
		// 数据加载成功关闭loading
		if (this.child) this.child.handleLoading();
	}

	componentWillUnmount() {
		// 组件销毁前将静止让setState修改state的状态
		this.setState = (state, callback) => {
			return;
		};
	}
	updateState = (state) => {
		this.setState(state, () => {
			if (this.state.selectPatient.patNo) {
				this.onClickRowPublicTop(this.state.selectPatient);
				this.getTemplateList();
			}
		});
	};
	onClickRowPublicTop = (record) => {
		if (!record.patNo && !this.state.patientData.patID) {
			return;
		}
		var data = {
			params: [
				{
					number: record.patNo || this.state.patientData.patID, // 登记号/身份证号
					cardTypeID: '', //卡类型id
					cardNo: '' //卡号
				}
			]
		};
		$http.post('urlS', this, {
			code: '03040004',
			data: data,
			success: function (res) {
				let errorCode = res.errorCode;
				if (errorCode === '0') {
					this.setState({
						userInfo: res.data || [] // 用户数据
					});
				}
			}
		});
	};
	//获取模板
	getTemplateList = () => {
		var that = this;
		let data = {
			params: [
				{
					hospID: user.hospID,
					admID: that.state.selectPatient.admID || that.state.patientData.admID,
					useFlag: 'N'
				}
			]
		};
		$http.post('urlDeault', this, {
			code: '10020001',
			data: data,
			success: function (res) {
				let activeKey = that.state.activeKey;
				if (res.result.TemplateList.length > 0 && activeKey == 0) {
					activeKey = res.result.TemplateList[0].id;
					if (!that.state.columns[activeKey]) {
						this.getTemplateColumns(res.result.TemplateList[0].id);
						this.getTemplateData(res.result.TemplateList[0].id);
					} else {
						this.getTemplateData(that.state.activeKey);
					}
				} else {
					this.getTemplateData(that.state.activeKey);
				}
				that.setState(
					{
						templateList: res.result.TemplateList,
						activeKey: activeKey,
						iEMRTemplateflag: res.result.iEMRTemplateflag
					},
					() => {
						that.child.handleLoading();
					}
				);
			}
		});
	};
	//获取列头
	getTemplateColumns = (id) => {
		let that = this;
		$http.post('urlDeault', this, {
			code: '10020015',
			data: {
				params: [
					{
						IEMRTemplateID: id
					}
				]
			},
			success: function (res) {
				let errorCode = res.errorCode;
				if (errorCode == '0') {
					var columnsArr = [];
					for (var i = 0; i < res.result.length; i++) {
						var data = res.result;
						let column = {
							title: data[i].IEMRTempElementDesc,
							dataIndex: data[i].IEMRTempElementCode,
							key: data[i].IEMRTempElementCode,
							align: 'left',
							width: '120px'
						};
						columnsArr.push(column);
					}
					columnsArr = that.state.endColumns.concat(columnsArr);
					let columns = that.state.columns;
					if (!columns[id]) {
						columns[id] = columnsArr;
					}
					that.setState({
						columns: columns
					});
				}
			}
		});
	};
	/**
	 * 获取模板数据
	 * @param {模板ID} templateID  
	 */
	getTemplateData = (templateID) => {
		let that = this;
		$http.post('urlDeault', this, {
			code: '04220014',
			data: {
				params: [
					{
						templateID: templateID,
						admID: that.state.selectPatient.admID || that.state.patientData.admID,
						startDate: this.state.admDateFrom,
						endDate: this.state.admDateTo
					}
				],
				pagination: [
					{
						pageSize: this.state.pageSize,
						currentPage: this.state.page
					}
				]
			},
			success: function (res) {
				let errorCode = res.errorCode;
				if (errorCode == '0') {
					that.setState({
						dataSource: res.result,
						total: res.total
					});
				}
			}
		});
	};
	setRowClassNamePublic2 = (record) => { };
	//点击tab页签
	onTabChange = (tab) => {
		this.setState(
			{
				activeKey: tab
			},
			() => {
				this.child.handleLoading();
				if (!this.state.columns[tab]) {
					this.getTemplateColumns(tab);
				}
				this.getTemplateData(tab);
			}
		);
	};
	// 调用公共组件的连接事件
	onRef = (ref) => {
		this.child = ref;
	};

	// 操作行
	onClickRowPublic1 = (record) => {
		return {
			// 单击行选中
			onClick: () => {
				this.setState({ emrRecordID: record.id }, () => {
					//this.dataTable2Data();
				});
			}
		};
	};
	// 选中行操作
	setRowClassNamePublic1 = (record) => {
		return record.id === this.state.emrRecordID ? 'clickRowStyle' : '';
	};
	startChange(date) {
		this.setState({
			admDateFrom: date
		});
	}
	endChange(date) {
		this.setState({
			admDateTo: date
		});
	}
	/**
		 * 查询数据
		 */
	searchData = () => {
		this.getTemplateData(this.state.activeKey);
	};

	// 提供修改page和pageSize的回调函数
	compilePage(page, pageSize) {
		// 修改page，或者pageSize
		this.setState({ page1: page, pageSize1: pageSize }, () => {
			// 重新调用查询方法
			this.searchData();
		});
	}
	handlePrint = () => {
		/*
		if ((user.hospID == 25) || (user.hospID == 50) || (user.hospID == 52) || (user.hospID == 55) || (user.hospID == 62) || (user.hospID == 63) || (user.hospID == 64) || (user.hospID == 65) || (user.hospID == 66) || (user.hospID == 67) || (user.hospID == 68)|| (user.hospID == 57)) {
			this.handlePrintOLD()
		} else {
			this.handlePrintNew()
		}
		*/
		if (this.state.iEMRTemplateflag==='Y') {
			this.handlePrintNew()
		} else {
			this.handlePrintOLD()
		}
	};
	handlePrintOLD = () => {
		let that = this;
		let data = {};
		data = {
			params: [
				{
					templateID: that.state.activeKey,
					admID: that.state.selectPatient.admID || that.state.patientData.admID,
					patID: that.state.selectPatient.patID || that.state.patientData.patID,
					hospID: user.hospID
				}
			]
		};
		$http.post('urlS', this, {
			code: '04220015',
			data: data,
			success: function (res) {
				if (res.errorCode == '0') {
					//加载模板
					LODOP = getLodop();
					LODOP.PRINT_INIT(res.result.template); //打印初始化
					eval(res.result.data); //执行打印内容
				}
			}
		});
	};
	handlePrintNew = async () => {
		let that = this;
		let data = {};
		data = {
			params: [
				{
					templateID: that.state.activeKey,
					admID: that.state.selectPatient.admID || that.state.patientData.admID,
					patID: that.state.selectPatient.patID || that.state.patientData.patID,
					hospID: user.hospID
				}
			]
		};
		let res = await React.$asyncPost(this, '04220020', data);
		if (res.errorCode == '0') {
			let result = res.result
			let template = result.template
			let data = result.data
			for (var i = 0; i < data.length; i++) {
				var dataResult = data[i];
				$fastReportTemplate(result.template, user.hospID, dataResult, "");
			}
		}
	};
	render() {
		// 组件所需参数
		const param = {
			// 表头配置
			columns: this.state.columns[this.state.activeKey],
			// 表格数据
			data: this.state.dataSource,
			// 数据总条数
			total: this.state.total,
			// 数据页数
			page: this.state.page,
			// x: 1600,
			height: store.getState().tableHeight.y - 15,
			y: store.getState().tableHeight.y,
			x: 900,
			isOnRow: true,
			rowClassName: true
		};
		let TabPaneArr = [];
		this.state.templateList.map((item) => {
			TabPaneArr.push(
				<TabPane tab={item.IEMRTemplateDesc} key={item.id}>
					<div className="condition">
						<RangeDatePicker
							format="YYYY-MM-DD"
							label="时间:"
							labelwidth="50px"
							totalwidth="350"
							width="280px"
							float="left"
							startDate={this.state.admDateFrom}
							endDate={this.state.admDateTo}
							// defaultValue={[moment(this.state.defaultValueObj.stDate, dateFormat), moment(this.state.defaultValueObj.endDate, dateFormat)]}
							startChange={this.startChange.bind(this)}
							endChange={this.endChange.bind(this)}
						/>
						<Button type="primary" style={{ margin: '0 25px', width: 100 }} onClick={this.searchData}>
							查询
						</Button>
						<Button type="primary" style={{ margin: '0 25px', width: 100 }} onClick={this.handlePrint}>
							打印
						</Button>
					</div>
					{this.state.activeKey == item.id ? (
						<PubilcTablePagination
							param={param}
							handelThis={this}
							onRef={this.onRef}
							onClickRowPublic={this.onClickRowPublic1}
							setRowClassNamePublic={this.setRowClassNamePublic1}
						/>
					) : (
						''
					)}
				</TabPane>
			);
		});
		return (
			<div style={{ width: '100%', height: '100%' }} className="mobile-care-form-record">
				<Row style={{ height: '100%', width: '100%', overflow: 'hidden' }}>
					<Col
						className={this.state.iconType == 'double-left' ? '' : 'visibleIcon'}
						span={this.state.leftspan}
						style={{
							border: this.state.iconType == 'double-left' ? '1px solid #cccccc' : '0px',
							height: '100%',
							overflowY: 'hidden',
							background: '#ffffff',
							boxSizing: 'border-box'
						}}
					>
						<PatientList type="radio" updateState={this.updateState} iconType={this.state.iconType} />
					</Col>
					<Col span={this.state.rightspan} style={{ border: '1px solid #cccccc', height: '100%' }}>
						<Row>
							<Col span={10}>
								<div>
									<TipHeader
										userInfo={this.state.userInfo}
										key={this.state.userInfo.patID + this.state.userInfo.accTSubID}
									/>
								</div>
							</Col>
							<Col span={14} className="otherInfo">
								<Row>
									<Col span={4} style={{ textAlign: 'center', background: '#F7FBFF' }}>
										<div className="payBox">
											<p className="p2" style={{ color: '#007AFF' }}>
												￥<span>{this.state.selectPatient.patBillTCAmt || '0'}</span>
											</p>
											<p>统筹金额</p>
										</div>
									</Col>
									<Col
										span={4}
										style={{ textAlign: 'center', background: '#F7FBFF', marginLeft: 10 }}
									>
										<div className="payBox">
											<p className="p2" style={{ color: '#007AFF' }}>
												￥<span>{this.state.selectPatient.patBillAllowAmt || '0'}</span>
											</p>
											<p>优惠</p>
										</div>
									</Col>
									<Col
										span={4}
										style={{ textAlign: 'center', background: '#F7FBFF', marginLeft: 10 }}
									>
										<div className="payBox">
											<p className="p2" style={{ color: '#007AFF' }}>
												￥<span>{this.state.selectPatient.patBillZFAmt || '0'}</span>
											</p>
											<p>个人自费</p>
										</div>
									</Col>
									<Col
										span={4}
										style={{ textAlign: 'center', background: '#F7FBFF', marginLeft: 10 }}
									>
										<div className="payBox">
											<p className="p2" style={{ color: '#007AFF' }}>
												{/* accYJPayAmt */}
												{/* /**
												* @By zxz: 预交金没有值
												* Create 2022-06-20
												* */ }
												￥<span>{this.state.selectPatient.accDepositIP || '0'}</span>
											</p>
											<p>预交金</p>
										</div>
									</Col>
									<Col
										span={4}
										style={{ textAlign: 'center', background: '#F7FBFF', marginLeft: 10 }}
									>
										<div className="payBox">
											<p className="p2" style={{ color: '#007AFF' }}>
												{/* opBalance */}
												{/* /**
												* @By zxz: 没有值
												* Create 2022-06-20
												* */ }
												￥<span>{this.state.selectPatient.purposeBlanceIP || '0'}</span>
											</p>
											<p>当前余额</p>
										</div>
									</Col>
								</Row>
							</Col>
						</Row>
						<Card style={{ height: store.getState().tableHeight.y + 135 + 'px', marginTop: 10 }}>
							<Tabs onChange={this.onTabChange} activeKey={this.state.activeKey}>
								{TabPaneArr}
							</Tabs>
						</Card>
					</Col>
				</Row>
			</div>
		);
	}
}

export default NurseEmrRecord;
